#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.DispatcherServlet;


public class WebAppInit implements WebApplicationInitializer {

	public void onStartup(ServletContext container) throws ServletException {
		// Create the 'root' Spring application context
		AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
		rootContext.register(AppConfig.class);
		rootContext.getEnvironment().setDefaultProfiles("embedded");

		// Manage the lifecycle of the root application context
		container.addListener(new ContextLoaderListener(rootContext));

		// Create the dispatcher servlet's Spring application context
		AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
		dispatcherContext.register(WebContextConfig.class);

		// Register and map the dispatcher servlet
		ServletRegistration.Dynamic dispatcher = container.addServlet(
				"dispatcher", new DispatcherServlet(dispatcherContext));
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping("/");
		
		// Enable hidden _method to override a form post
		container.addFilter("hiddenMethodFilter", new HiddenHttpMethodFilter())
		.addMappingForServletNames(null, true, "dispatcher");

		// H2 Database Console for managing the app's database
		// (borrowed this concept from greenhouse spring PoC)
		ServletRegistration.Dynamic h2Servlet = container.addServlet(
				"H2Console", org.h2.server.web.WebServlet.class);
		h2Servlet.setInitParameter("webAllowOthers", "true");
		h2Servlet.setLoadOnStartup(2);
		h2Servlet.addMapping("/admin/h2/*");
	}

}
